<template>
  <div class="line-page">
    <a-card :bordered="false">
      <!-- 表格顶部搜索部分 -->
      <c-table-search-form
        v-model="tableSearchForm"
        :datas="tableSearchFormData"
        @onAdd="onAdd('', 'add')"
      >
      </c-table-search-form>

      <!-- 表格部分 -->
      <c-table
        :columns="tableColumns"
        :datas="tableData"
        :loading="loading"
        showPagination
        :paginationDatas="paginationDatas"
        @onPageSizeChange="onPageSizeChange"
        @onShowNumChange="onShowNumChange"
      >
        <!-- 表格自定义部分 -->
        <!-- 创建时间 -->
        <template slot="createDate" slot-scope="createDate">
          <span>
            {{ $getTime(createDate.tableRow) }}
          </span>
        </template>

        <!-- 表格操作按钮 -->
        <template slot="handle" slot-scope="row">
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="onDel(row.tableRow.id)"
          >
            <p slot="title">
              是否确认要删除该线路？
            </p>
            <a type="link"><a-icon type="delete" /> 删除</a>
          </a-popconfirm>
        </template>
      </c-table>

      <!-- 新增 -->
      <a-modal
        title="新增线路"
        :visible="dialogVisible"
        width="30%"
        @cancel="onCancel"
        :confirm-loading="confirmLoading"
        :destroyOnClose="true"
      >
        <a-form-model
          :model="form"
          ref="formModels"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 14 }"
        >
          <a-form-model-item
            label="线路起点："
            prop="startCompanyId"
            :rules="{
              required: true,
              message: '请输入起点',
              trigger: 'change'
            }"
          >
            <a-select
              :loading="lineSelectoading"
              @focus="lineSelectFocus"
              showSearch
              option-filter-prop="children"
              v-model="form.startCompanyId"
              placeholder="请选择或搜索线路起点"
            >
              <a-select-option
                v-for="item in allCompanySelectList"
                :key="item.id"
                :value="item.id"
                >{{ item.companyName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>

          <!-- 线路增删内容块 -->
          <div
            class="lineOperation"
            v-for="(item, index) in form.lineOperationList"
            :key="index"
          >
            <!-- 线路 -->
            <a-form-model-item
              :label="'线路节点' + Number(index + 1) + '：'"
              :prop="'lineOperationList.' + index + '.companyId'"
              :rules="{
                required: true,
                message: '请输入线路节点' + Number(index + 1),
                trigger: 'change'
              }"
            >
              <div class="position-relative">
                <a-select
                  :loading="lineSelectoading"
                  @focus="lineSelectFocus"
                  v-model="item.companyId"
                  showSearch
                  option-filter-prop="children"
                  :placeholder="'请选择或搜索线路节点' + Number(index + 1)"
                >
                  <a-select-option
                    v-for="item in allCompanySelectList"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.companyName }}</a-select-option
                  >
                </a-select>
                <a-icon
                  class="form-icon margin-l10 cursor-pointer display-inline-block"
                  :class="index === 0 ? 'colorMain ' : 'colorRed '"
                  :type="index === 0 ? 'plus-circle' : 'minus-circle'"
                  @click="onLineOperationHandle(index)"
                />
              </div>
            </a-form-model-item>
            <!-- 差价 -->
            <a-form-model-item
              label="差价："
              :prop="'lineOperationList.' + index + '.priceDifference'"
              :rules="{
                required: true,
                message: '请输入差价',
                trigger: 'change'
              }"
            >
              <a-input-number
                style="width:100%"
                v-model="item.priceDifference"
                placeholder="请输入差价"
                :formatter="
                  value => {
                    let reg = numRes;
                    return `${value}`
                      .replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                      .replace(reg, '$1$2.$3');
                  }
                "
                :parser="
                  value => {
                    let reg = numRes;
                    return value
                      .replace(/\s?|(,*)/g, '')
                      .replace(reg, '$1$2.$3');
                  }
                "
              ></a-input-number>
            </a-form-model-item>
          </div>
        </a-form-model>
        <span slot="footer" class="dialog-footer flex-center" >
          <a-space>
             <a-button @click="onCancel">取消</a-button>
             <a-button type="primary" @click="onSubmit">确认提交</a-button>
          </a-space>
        </span>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
import {
  getLinePage,
  deleteLine,
  addLine,
  getAllCompanyWithoutSelect
} from "@/api/line/index";
export default {
  name: "Lines",
  components: {},
  data() {
    return {
      numRes: /^(-)*(\d+)\.(\d\d).*$/,
      dialogVisible: false,
      confirmLoading: false,
      lineSelectoading: false,
      form: {
        startCompanyId: undefined, // 起点
        lineOperationList: [this.constructorObj()] // 线路操作块数组
      },
      tableSearchForm: {},

      tableSearchFormData: [
        {
          prop: "addBtn",
          type: "addBtn"
        }
      ],
      tableColumns: [
        {
          title: "序号",
          dataIndex: "id",
          align: "center",
          width: 120
        },
        {
          title: "线路",
          dataIndex: "line",
          align: "center"
        },
        {
          title: "差价",
          dataIndex: "priceDifference",
          align: "center"
        },
        {
          title: "创建时间",
          dataIndex: "createDate",
          align: "center",
          scopedSlots: { customRender: "createDate" }
        },
        {
          title: "操作",
          key: "handle",
          scopedSlots: { customRender: "handle" },
          align: "center",
          width: 150
        }
      ],
      tableData: [],
      filterIdArr: [],
      allCompanySelectList: [],
      paginationDatas: {
        pageSizeOptions: ["10", "20", "30", "40", "50", "200", "1000"],
        pageSize: 10,
        pageNum: 1,
        total: 0
      }
    };
  },
  created() {
    this.onPageOnlod();
    // this.getLineSelectList([]);
  },
  mounted() {},
  methods: {
    lineSelectFocus() {
      this.getLineSelectList();
    },
    //获取选择列表
    getLineSelectList() {
      this.lineSelectoading = true;
      this.form.lineOperationList.forEach(item => {
        if (item.companyId) {
          this.filterIdArr.push(item.companyId);
        }
      });

      this.filterIdArr = this.form.startCompanyId
        ? this.filterIdArr.concat([this.form.startCompanyId])
        : this.filterIdArr;
      this.filterIdArr = [...new Set(this.filterIdArr)];
      getAllCompanyWithoutSelect(this.filterIdArr)
        .then(res => {
          this.lineSelectoading = false;
          this.allCompanySelectList = res.data;
        })
        .catch(() => {});
    },
    //获取列表数据
    onPageOnlod() {
      this.loading = true;
      getLinePage({
        pageData: {
          ...{
            pageSize: this.paginationDatas.pageSize,
            pageNum: this.paginationDatas.pageNum
          }
        }
      })
        .then(res => {
          this.tableData = res.data.pageData;
          this.paginationDatas.total = res.data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    onShowNumChange(val) {
      this.paginationDatas.pageNum = val;
      this.onPageOnlod();
    },
    onPageSizeChange(val) {
      this.paginationDatas.pageSize = val;
      this.onPageOnlod();
    },
    onAdd(row) {
      this.form.startCompanyId  = undefined
      this.form.lineOperationList = [this.constructorObj()];
      this.dialogVisible = true;
    },
    onOK() {
      this.dialogVisible = false;
    },
    onCancel() {
      this.dialogVisible = false;
    },
    constructorObj() {
      return {
        companyId: undefined,
        priceDifference: undefined,
        nodeOrder: undefined
      };
    },
    onLineOperationHandle(index) {
      if (index === 0) {
        this.form.lineOperationList.push(this.constructorObj());
      } else {
        this.form.lineOperationList.splice(index, 1);
      }
    },
    //提交
    onSubmit() {
      const that = this;
      this.$refs.formModels.validate().then(data => {
        this.form.lineOperationList.forEach((item, index) => {
          item.nodeOrder = index + 1;
        });
        const parmas = {
          startCompanyId: this.form.startCompanyId,
          nodeList: this.form.lineOperationList
        };
        that.confirmLoading = true;
        addLine(parmas)
          .then(res => {
            that.$message.success("操作成功");
            that.onPageOnlod();
            that.confirmLoading = false;
             this.dialogVisible = false;
            that.visible = false;
          })
          .catch(() => {
            this.confirmLoading = false;
             this.dialogVisible = false;
          });
      });
    },
    //删除
    onDel(id) {
      deleteLine({
        lineId: id
      }).then(res => {
        this.$message.success("操作成功");
        this.onPageOnlod();
      });
    }
  }
};
</script>

<style lang="less" scoped>
.form-icon {
  position: absolute;
  top: 50%;
  right: -50px;
  transform: translate(-50%, -50%);
}
</style>
